﻿using Cinch;
using FR.SAFTAnalyser.Model;
using MEFedMVVM.Common;
using System.Linq;

namespace FR.SAFTAnalyser.ViewModels
{
    public class TaxViewModel : WorkspaceViewModel
    {
        public TaxViewModel()
        {
            if (!Designer.IsInDesignMode)
            {
                Mediator.Instance.Register(this);
                this.DisplayName = "Impostos";
            }
        }

        [MediatorMessageSink(MessageType.SAFT_FILE_OPENED)]
        private void LoadTax(AuditFile saft)
        {
            if (saft != null && saft.MasterFiles != null)
                this.TaxTable = saft.MasterFiles.TaxTable;
        }

        TaxTableEntry[] taxTable;
        public TaxTableEntry[] TaxTable
        {
            get { return taxTable; }
            set
            {
                taxTable = value;
                NotifyPropertyChanged(ObservableHelper.CreateArgs<TaxViewModel>(x => x.TaxTable));
            }
        }

        string filter;
        public string Filter
        {
            get { return filter; }
            set
            {
                filter = value;

                if (SAFT.SaftAnalyser.Instance.SaftFile != null)
                {
                    if (string.IsNullOrEmpty(filter))
                        this.TaxTable = SAFT.SaftAnalyser.Instance.SaftFile.MasterFiles.TaxTable;
                    else
                    {
                        this.TaxTable =
                            (from c in SAFT.SaftAnalyser.Instance.SaftFile.MasterFiles.TaxTable
                             where !string.IsNullOrEmpty(c.Description) && c.Description.IndexOf(filter, System.StringComparison.OrdinalIgnoreCase) >= 0 ||
                                 !string.IsNullOrEmpty(c.TaxCode) && c.TaxCode.IndexOf(filter, System.StringComparison.OrdinalIgnoreCase) >= 0 ||
                                 !string.IsNullOrEmpty(c.TaxCountryRegion) && c.TaxCountryRegion.IndexOf(filter, System.StringComparison.OrdinalIgnoreCase) >= 0 ||
                                 c.TaxExpirationDateSpecified && c.TaxExpirationDate.ToString("yyyy-MM-dd").IndexOf(filter, System.StringComparison.OrdinalIgnoreCase) >= 0 ||
                                 c.TaxType.ToString().IndexOf(filter, System.StringComparison.OrdinalIgnoreCase) >= 0
                             select c).ToArray();
                    }
                }
            }
        }
    }
}
